<script>
import { onBeforeUnmount,onMounted, ref,shallowRef } from 'vue';
import useMailApi from '@/api/useMailApi';
import truncate from 'truncate-html';
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessageBox } from 'element-plus'

const { listMail, addMail, listUserMail } = useMailApi();


export default {
  components: { Editor, Toolbar },
  setup() {

    const editorRef = shallowRef()

    const submitSuccessDialogVisible = ref(false)

    const valueHtml = ref()

    const toolbarConfig = {}

    const editorConfig = { placeholder: '请输入内容...' }

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    onMounted(() => {
      setTimeout(() => {
        valueHtml.value =''
      }, 1500)
    })
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })
    const searchModel = ref({
      num: 2,
      pageNo: 1,
      pageSize: 10
    });
    const total = ref(0);
    const mailList = ref([]);
    const loading = ref(false);  // Define loading here
    const submitMailDialogVisible = ref(false);
    const content = ref('');

    const rules = ref({
      reply: [{ required: true, message: '请输入信件内容', trigger: 'blur' }]
    });

    const handleEditorCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，很重要！
    };

    const formatDate = (date) => {
      if (!date) return ''; // 处理日期为空的情况

      // 将日期字符串解析为日期对象
      const datee = new Date(date.replace(/T/, ' ').replace(/Z/, ''));

      // 判断是否成功解析
      if (!isNaN(datee.getTime())) {
        // 使用 toLocaleDateString 获取年月日部分
        return datee.toLocaleDateString('en-US', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        });
      } else {
        return 'Invalid Date';
      }
    }

    const getMailList = () => {
      mailList.value = [];
      loading.value = true;

      listMail(searchModel.value)
          .then(response => {
            mailList.value = response.data.rows;
            total.value = response.data.total;
          })
          .catch(error => {
            console.error(error);
          })
          .finally(() => {
            loading.value = false;
          });
    };

    const queryUserMailList = () => {
      const userModel = {
        pageNo: searchModel.value.pageNo,
        pageSize: searchModel.value.pageSize
      };

      listUserMail(userModel)
          .then(response => {
            mailList.value = response.data.rows;
            total.value = response.data.total;
          })
          .catch(error => {
            console.error(error);
          });
    };

    const handleSizeChange = (pageSize) => {
      searchModel.value.pageSize = pageSize;
      getMailList();  // Add parentheses to call the function
    };

    const handleCurrentChange = (pageNo) => {
      searchModel.value.pageNo = pageNo;
      getMailList();
    };

    const getPreviewContent = (content) => {
      const truncatedContent = truncate(content, 5, { byWords: true });
      return truncatedContent;
    };

    const shouldShowButton = (content) => {
      function escapeHtml(html) {
        const textArea = document.createElement('textarea');
        textArea.innerHTML = html;
        return textArea.value;
      }

      function getEscapedContentLength(content) {
        const escapedContent = escapeHtml(content);
        const truncatedContent = truncate(escapedContent, 5, { byWords: true });
        return truncatedContent.length;
      }

      return getEscapedContentLength(content) > 5;
    };

    const toggleShowFullContent = (row) => {
      if (row.content) {
        ElMessageBox.alert(row.content, '完整内容', {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true
        });
      }
    };

    const toggleShowFullReply = (row) => {
      if (row.reply) {
        ElMessageBox.alert(row.reply, '完整回复', {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true
        });
      }
    };

    const openSubmitMailUI = () => {
      submitMailDialogVisible.value = true;
      content.value = '';
      valueHtml.value = ''; // 清空富文本内容
    };

    const submitMail = () => {
      content.value = valueHtml.value;
      addMail(content.value)
          .then(response => {
            submitMailDialogVisible.value = false;
            getMailList();
            submitSuccessDialogVisible.value = true; // 提交成功后显示成功弹窗

            // 使用 ElMessageBox 显示提交成功的弹窗
            ElMessageBox.alert('提交成功', '提示', {
              confirmButtonText: '确定',
              type: 'success',
            });
          })
          .catch(error => {
            console.error(error);
          });
    };

    return {
      submitSuccessDialogVisible,
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleEditorCreated,
      searchModel,
      total,
      mailList,
      loading,
      submitMailDialogVisible,
      content,
      rules,
      getMailList,
      queryUserMailList,
      submitMail,
      handleSizeChange,
      handleCurrentChange,
      getPreviewContent,
      shouldShowButton,
      toggleShowFullContent,
      toggleShowFullReply,
      openSubmitMailUI,
      formatDate
    };


  },

  created() {
    this.getMailList();
  }
};
</script>

<template>
  <div>
    <!-- 结果列表 -->
    <el-card>
      <el-table :data="mailList" stripe style="width: 100%">
        <el-table-column label="#" width="80">
          <template #default="{ $index }">
            {{ (searchModel.pageNo - 1) * searchModel.pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" width="400">
          <template #default="{ row }">
            <div class="content-preview" v-html="getPreviewContent(row.content)"></div>
            <el-button v-if="shouldShowButton(row.content)" type="text" @click="toggleShowFullContent(row)">查看全部</el-button>
          </template>
        </el-table-column>

        <!-- 回复列 -->
        <el-table-column prop="reply" label="回复" width="400">
          <template #default="{ row }">
            <div class="content-preview" v-html="getPreviewContent(row.reply)"></div>
            <el-button v-if="shouldShowButton(row.reply)" type="text" @click="toggleShowFullReply(row)">查看全部</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="提交时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="button-container">
      <el-button type="primary" @click="openSubmitMailUI">提交信件</el-button>
      <el-button type="primary" @click="queryUserMailList">查询我的信件</el-button>
      <el-button type="primary" @click="getMailList">查询全部信件</el-button>
    </div>

    <!-- 分页组件 -->
    <el-pagination
        :current-page="searchModel.pageNo"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="searchModel.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <div>


      <!-- 信件提交弹窗 -->
      <el-dialog v-model="submitMailDialogVisible"
                 title="提交信件"
                 width="50%"
                 @close="submitMailDialogVisible = false"
                 transition="dialog-fade"
      >
        <el-form :model="{ content }" :rules="rules"  label-width="80px" style="display: flex; flex-direction: column;">
          <el-form-item label="信件内容" prop="content" style="flex: 1;">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
            />
<!--            <Editor style="width: 100%; height: 300px;" v-model="content" @onCreated="handleEditorCreated" />-->
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitMail">提交信件</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.dialog-fade-enter-active, .dialog-fade-leave-active {
  transition: opacity 0.5s;
}
.dialog-fade-enter, .dialog-fade-leave-to {
  opacity: 0;
}
.el-button--primary {
  background-color: #67c23a;
  border-color: #67c23a;
}
.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}
.button-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.button-container .el-button {
  margin-left: 10px;
}
</style>